<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <div class="flex items-center">
        <div class="border-arrow" @click="toPrevPage">
          <FontIcon icon="icon-left" />
        </div>
        <div class="text-[#242930] ml-4">
          {{ getName() }}{{ t("formula_detail.add_material") }}
        </div>
      </div>
    </vxe-card>

    <vxe-card title="" class="w-full mt-[16px]" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <AuTable
      ref="tableRef"
      v-bind="gridOption"
      class="mt-[16px]"
      @actionClick="actionClick"
    />

    <vxe-card title="" class="w-full mt-[16px]" :border="false">
      <el-button
        type="primary"
        style="float: right"
        @click="saveFormulaMaterial"
      >
        {{ t("buttons.confirm") }}
      </el-button>
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";
import { useI18n } from "vue-i18n";

import {
  MaterialProp,
  getMaterialList,
  getMaterialListForFormula
} from "@/api/cabinet/material";

import { GetListParamProp } from "@/api/user";
import { ElMessage, ElMessageBox, ImageProps } from "element-plus";
import { onBeforeRouteLeave, useRouter, useRoute } from "vue-router";
import { isString, useGlobal } from "@pureadmin/utils";
import { emitter } from "@/utils/mitt";

import { VxeGridInstance, VxeGridProps, VxeUI } from "vxe-table";

defineOptions({
  name: "CabinetDetailMaterial"
});
const { t } = useI18n();
const dateValue = ref("");
const size = ref<"default" | "large" | "small">("default");

const { proxy } = getCurrentInstance();

// region 页面及组件变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();
const route = useRoute();

const showUploadModal = ref(false);

const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formula_detail.material_name",
    placeholder: "formula_detail.material_name_placeholder"
  }
]);

const showDetailModal = ref(false);
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showCheckbox: true,
  showExportBtn: false,
  columns: [
    { field: "id", title: "formula_detail.material_id" },
    { field: "name", title: "formula_detail.material_name" },
    {
      field: "type_name",
      title: "formula_detail.material_type"
    }
  ],
  actions: [],
  operateTools: [],
  dataSource: [],
  vxeTableConfig: {
    pagerConfig: {
      enabled: false
    }
  }
});
const rowData = ref({});
const formulaId = ref(route.query.id as string);

let query = {};

const formRef = ref();
const tableRef = ref();

// endregion

// region 页面公共方法集合
function storageConfigureChange<T>(key: string, val: T): void {
  const storageConfigure = $storage.configure;
  storageConfigure[key] = val;
  // $storage.configure = storageConfigure;
}

const getName = () => {
  try {
    const version = JSON.parse(route.query.version as string);
    return version.name;
  } catch (error) {
    return "";
  }
};

async function getMaterialData() {
  const res = await getMaterialList({
    size: 0,
    publish_status: 1,
    ...formRef.value.getFormData()
  });
  gridOption.dataSource = res.data;
}

// endregion

// region 页面及组件事件集合
const toPrevPage = () => {
  // router.go(-1);
  //window.history.back();
  router.push({
    name: "CabinetFormulaDetail",
    query: {
      ...proxy.$route.query
    }
  });
};

const search = () => {
  getMaterialData();
};

const actionClick = ({
  key,
  row
}: {
  key: ACTION_TYPE | string;
  row: MaterialProp;
}) => {
  switch (key) {
    case ACTION_TYPE.TADD:
      break;
    case ACTION_TYPE.EDIT:
      break;
    case ACTION_TYPE.TDELETE:
      break;
    default:
      break;
  }
};

//保存选择
const saveFormulaMaterial = () => {
  console.log("保存配方物料");
  const arr = tableRef.value.getCheckboxRecords();
  console.log(arr);
  router.push({
    name: "CabinetFormulaDetail",
    query: {
      ...proxy.$route.query,
      matIds: JSON.stringify(arr.map(v => v.material_id))
    }
  });
};

//回显已选中的物料
const getMaterialListForSelect = () => {
  const params = { formula_subid: route.query.formula_subid };
  getMaterialListForFormula(params).then(res => {
    console.log(res.data);
    //tableRef.value.setCheckboxRow([10143, 10134, 10135, 10136], true);
  });
};

// 设置已选中的行
const setSelectRow = (rows: Record<string, any>[], checked: boolean) => {
  const $table = tableRef.value;
  if ($table) {
    console.log($table.vxeGridRef, rows);
    nextTick(() => {
      $table.vxeGridRef.setCheckboxRow(rows, checked);
    });
  }
};

onMounted(async () => {
  await getMaterialData();
  query = route.query;
  if (isString(route.query.matIds)) {
    const matIds = JSON.parse(route.query.matIds);
    const tableData = tableRef.value.vxeGridRef.getData();
    const filteredData = tableData.filter(item =>
      matIds.includes(item.material_id)
    );
    setSelectRow(filteredData, true);
  }
});
// getMaterialListForSelect();

// endregion
</script>
